package de.tub.bazinga.event;

import org.apache.log4j.Logger;

import de.tub.bazinga.audio.AudioManagerImpl;
import de.tub.bazinga.audio.IAudioManager;
import de.tub.bazinga.eventbus.IEventHandler;
import de.tub.bazinga.main.Bazinga;
import de.tub.bazinga.object.Target;
import de.tub.bazinga.object.TargetDefinition;

public class HitEventHandler implements IEventHandler<HitEvent> {

	private static Logger LOGGER = Logger.getLogger(HitEventHandler.class);
	private final IAudioManager audioManager = AudioManagerImpl.getInstance();

	private final Bazinga game;

	public HitEventHandler(Bazinga game) {
		super();
		this.game = game;
	}

	@Override
	public void handleEvent(HitEvent event) {
		LOGGER.info("' " + event.hitTargetCount() + "' Targets hit by "
				+ event.getPlayer());

		if (game.isRoundRunning() && event.allTargetsHit()) {
			int points = calculatePoints(event);
			event.getPlayer().addPoints(points);
			audioManager.playHitSound();
		}

	}

	private int calculatePoints(HitEvent event) {
		int points = 0;
		for (Target target : event.getTargets()) {
			long targetLifeTime = target.lifeTime();
			if (targetLifeTime > 10000) {
				points += 1;
			} else {
				points += (10 - Math.round(targetLifeTime / 1000));
			}

			TargetDefinition td = target.getTargetPostion();
			if (td.isMoveing()) {
				points = points * Math.abs(td.getMovement());
			}
		}
		return points;
	}

}
